<?php
/**
 * Pipahr
 *
 * @author Randy Zhao
 * @copyright 2013 pipahr.com
 */
JLoader::register("PCalendarModellistview", OC::$SERVERROOT."/apps/calendar/lib/listview.php");
JLoader::register('ProvinceHelper', JPATH_SITE.'/components/com_city/helper.php');
JLoader::register('PCalendarHelper', OC::$SERVERROOT."/apps/calendar/lib/helper.php");

class PCalendarController
{
   // calendar home page view
   public static function calendar() {
      // Check permission
      if(!PUtil::checkUserLogin(true))
         return;

      $userid = OC_USER::getUser();
      $master = PFactory::getMasterUser();

      // Create default calendar ...
      $calendar_model = new PCalendarModelCalendar();
      $object_model = new PCalendarModelObject();
      $calendars = $calendar_model->allCalendars($userid, false);
      if( count($calendars) == 0 ) {
         $calendar_model->addDefaultCalendars($userid);
         $calendars = $calendar_model->allCalendars($userid, true);
      }

      //Fix currentview for fullcalendar (if necessary)
      if(OCP\Config::getUserValue($userid, 'calendar', 'currentview', 'month') != "month") {
         OCP\Config::setUserValue($userid, "calendar", "currentview", "month");
      }

      $tmpl = new OCP\Template('calendar', 'calendar', 'user');

      //if(array_key_exists('showevent', $_GET)) {
      //   $tmpl->assign('showevent', $_GET['showevent']);
      //}
       
      $joblists = PResumesHelper::getJobList($master->id,10);
      $objects_number = $object_model->getObjectNumber($master->id);
      $tmpl->assign('objects_number',$objects_number);
      $tmpl->assign('joblists', $joblists);
      $tmpl->assign('calendarid', $calendars[0]['id']);
      $tmpl->assign('page_title', '面试管理');
      $tmpl->printPage();
   }

   // calendar reject page view
   public static function rejectview() {
      $token = JRequest::getString('t', '');
      $email = JRequest::getString('e', '');

      $error_msg = "";
      $object_model = new PCalendarModelObject();
      if ( empty($token) || empty($email) ) {
         $error_msg = "没有找到相关信息。";
      } else {
         // Check token valid
         if ( !$object_model->checkRejectToken($token, $email) ) {
            $error_msg = $object_model->getError();
         }
      }

      if ( !empty($error_msg) ) {
         header('HTTP/1.0 404 Not Found');
         $tmpl = new OCP\Template('', '404', 'base');
         $tmpl->assign('error', $error_msg);
         $tmpl->printPage();
         exit;
      }

      // Get basic info for view
      $basicInfo = $object_model->getBasicRejectPageInfo($token, $email);

      $tmpl = new OCP\Template('calendar', 'reject', 'base');
      $tmpl->assign('basicInfo', $basicInfo);
      $tmpl->assign('page_title', '放弃面试');
      $tmpl->printPage();
   }

   // Reject this interview invite
   public static function reject() {
      OC_JSON::setContentTypeHeader();

      $object_model = new PCalendarModelObject();
      if ( !$object_model->reject() ) {
         jexit(jsonError($object_model->getError(), null, false));
      }

      jexit(jsonSuccess('操作成功！', null, null, false));
   }

   /**
    * Show Calender list view
    * @return page view
    */
   public static function listview() {
      if(!PUtil::checkUserLogin(true))
         return;

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      $user = PFactory::getMasterUser();
      $joblists = PResumesHelper::getJobList($user->id,11);

      $app = PFactory::getApplication();
      $listorders = $app->getUserState('calendarlistdir', array('orderdir'=>'DESC'));

      $show_prev = $app->getUserState('calendar_showprev', 1);

      $model = new PCalendarModellistview();
      list($listview, $pagination) = $model->getList();
      
      $searchUrl = PCalendarHelper::getSearchUrl();

      $tmpl = new OCP\Template('calendar', 'calendar.list', 'user');
      $tmpl->assign('showlist', $listview);
      $tmpl->assign('listorders', $listorders);
      $tmpl->assign('show_prev', $show_prev);
      $tmpl->assign('joblists', $joblists);
      $tmpl->assign('searchUrl', $searchUrl);
      $tmpl->assign('viewURL', OCP\Util::linkToRoute('resume_view', array('id' => '')));
      $tmpl->assign('pagination', $pagination);
      $tmpl->assign('page_title', '面试管理');
      $tmpl->printPage();
   }

   public static function interviewfeedback(){
      $companyid = 0;
      if(!OC_User::isLoggedIn()) {
         $app = PFactory::getApplication();
         $companyid = $app->getUserState('calendarshare_companyid', 0);
         if(!$companyid) {
            OC_Response::redirect(OC_Helper::linkToRoute("company_login"));
            return;
         }
      } else {
         if (PFactory::isJobseekerUser()) {
            OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
            return;
         } else {
            $user = PFactory::getMasterUser();
            $companyid = $user->id;
         }
      }

      $model = new PCalendarModellistview();
      $objectid = JRequest::getInt('id', 0);
      $feedbackinformation = PCalendarHelper::getFeedbackinfoFromObjectid($objectid,$companyid);
      //$feedbackinformation = array_filter($feedbackinformation);
      if(empty($feedbackinformation)){
         header('HTTP/1.0 404 Not Found');
         $tmpl = new OCP\Template('', '404', 'base');
         $tmpl->assign('error', '没有找到相关信息。');
         $tmpl->printPage();
         exit;
      }

      $questionlist = $model->getFeedbackQuestion();
      $feedbacksuggestion = $model->getFeedbackSuggestion();

      // create a customized url for non-login case 
      if(!OC_User::isLoggedIn()) {
         // If share, get shared resume link
         $sharewith = JRequest::getString('w', '');
         $viewURL = PCalendarHelper::getResumeShareLink($feedbackinformation['jobseekerid'], $sharewith);
         $jobposURL =  OC_Helper::linkToRoute("jobpos_view",array('id' => ''));
      }
      else {
         $viewURL = OCP\Util::linkToRoute('resume_view', array('id' =>$feedbackinformation['jobseekerid'],
                                          'name'=>JFilterOutput::stringURLUnicodeSlug($feedbackinformation['jobseekername'])));
         $jobposURL = OC_Helper::linkToRoute("jobpos_setup",array('id' => ''));
      }

      $tmpl = new OCP\Template('calendar', 'calendar.interviewfeedback.preview', 'user');
      $tmpl->assign('absent', isset($feedbackinformation["suggestion_id"]) && $feedbackinformation["suggestion_id"] == 0 ? 1 : 0);
      $tmpl->assign('notattended', isset($feedbackinformation["suggestion_id"]) && $feedbackinformation["suggestion_id"] == 6 ? 1 : 0);
      $tmpl->assign('feedbackinformation', $feedbackinformation);
      $tmpl->assign('viewURL', $viewURL);
      $tmpl->assign('jobposURL', $jobposURL);
      $tmpl->assign('questionlist', $questionlist);
      $tmpl->assign('feedbacksuggestion', $feedbacksuggestion);
      $tmpl->assign('page_title', '面试管理');
      $tmpl->printPage();
   }

   public static function search() {
      $searchUrl = PCalendarHelper::getSearchUrl();

      if(PFactory::isJobseekerUser()) {
         OC_Response::redirect(OC_Helper::linkToRoute("jobseeker_home"));
         return;
      }

      if(!PUtil::checkUserLogin(true,$searchUrl)) {
         return;
      }

      $user = PFactory::getMasterUser();
      $joblists = PResumesHelper::getJobList($user->id,11);

      $app = PFactory::getApplication();
      $listorders = $app->getUserState('calendarlistdir', null);

      $show_prev = $app->getUserState('calendar_showprev', 0);

      $jobid = JRequest::getInt('jobid', 0);

      $model = new PCalendarModellistview();
      list($listview, $pagination) = $model->getList();

      $tmpl = new OCP\Template('calendar', 'calendar.list', 'user');
      $tmpl->assign('showlist', $listview);
      $tmpl->assign('listorders', $listorders);
      $tmpl->assign('joblists', $joblists);
      $tmpl->assign('show_prev', $show_prev);
      $tmpl->assign('searchUrl', $searchUrl);
      $tmpl->assign('viewURL', OCP\Util::linkToRoute('resume_view', array('id' => '')));
      $tmpl->assign('pagination', $pagination);
      $tmpl->assign('page_title', '面试管理');
      $tmpl->printPage();
   }

   public static function getjoblist() {
      // Get changejob from job, calender view dont need href
      $calview = JRequest::getInt('cview', 0);

      $companyid = 0;
      if(!OC_User::isLoggedIn()) {
         $app = PFactory::getApplication();
         $companyid = $app->getUserState('resumeshare_companyid', 0);
         if(!$companyid) {
            echo '您需要先登录';
            exit;
         }
      } else {
         if (PFactory::isJobseekerUser()) {
            echo '您不是企业用户';
            exit();
         } else {
            $user = PFactory::getMasterUser();
            $companyid = $user->id;
         }
      }

      $jobid = JRequest::getInt('jobid', 0);
      $jobcity = JRequest::getString('jc', '');
      $jobikey = JRequest::getString('ik', '');
      $keyword = JRequest::getString('q', '');
      $searchUrl = JRequest::getString('searchurl', OC_Helper::linkToRoute('calendar_search'));

      if (!empty($jobid)) {
         $jobdata = PResumesHelper::getJob($jobid);
         $jobcity = $jobdata->id_city;
         if(empty($jobcity)) {
            $jobcity = 'other';
         }
         $jobikey = $jobdata->ikey;
         if(empty($jobikey)) {
            $jobikey = 'other';
         }
      }

      if ( $calview ) {
         $cityPageUrl = $ikeyPageUrl = OCP\Util::linkToRoute('calendar_joblist', array('cview' => 1));
      } else {
         $cityPageUrl = $ikeyPageUrl = OC_Helper::linkToRoute('calendar_joblist');
      }

      if (!empty($keyword)) {
         list($cityPageUrl, $selected) = PResumesHelper::getSearchItemHref($cityPageUrl, 'q', $keyword);
      }
      if (!empty($jobcity)) {
         list($cityPageUrl, $selected) = PResumesHelper::getSearchItemHref($cityPageUrl, 'jc', $jobcity);
      }
      if (!empty($jobikey)) {
         list($ikeyPageUrl, $selected) = PResumesHelper::getSearchItemHref($cityPageUrl, 'ik', $jobikey);
      } else {
         list($ikeyPageUrl, $selected) = PResumesHelper::getSearchItemHref($cityPageUrl, 'ik', 'all');
      }
   
      $jobcitylist = PResumesHelper::getJobCityList($companyid);
      $jobikeylist = PResumesHelper::getJobIkeyList($companyid);

      $jobList = PResumesHelper::getJobList($companyid, 0, $keyword, $jobcity, $jobikey);

      $tmpl = new OCP\Template('calendar', 'calendar.list.joblist', '');
      if ( $calview ) {
         $tmpl->assign('calview', true);
      }
      $tmpl->assign('cityPageUrl', $cityPageUrl);
      $tmpl->assign('ikeyPageUrl', $ikeyPageUrl);
      $tmpl->assign('searchUrl', $searchUrl);
      $tmpl->assign('jobcitylist', $jobcitylist);
      $tmpl->assign('jobikeylist', $jobikeylist);
      $tmpl->assign('jobList', $jobList);
      $tmpl->assign('cur_jobid', $jobid);
      $tmpl->printPage();
   }
   
   public static function sendoffer(){
      if (!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }

      $post = JRequest::get("post");
      $objectid = JRequest::getInt('objectid',0);
      $object_model = new PCalendarModelObject();

      // Check CURD Permissions
      if ( !$object_model->checkPermissions($post) ) {
         jexit(jsonError($object_model->getError(), null, false));
      }

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      $cal = JRequest::getInt('calendar', 0);
      $vcalendar = $object_model->createVCalendarFromRequest($post);

      if(!$object_model->sendOffer($cal, $vcalendar->serialize(), $post)) {
         jexit(jsonError($object_model->getError(), null, false));
      }
      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function setinterviewresult(){
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }
      $objectid = JRequest::getInt('objectid',0);
      $model = new PCalendarModellistview();
      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      if ( !$model->setInterviewResult() ) {
         jexit(jsonError('网络异常，请刷新重试!', null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function setofferresult(){
      OC_JSON::setContentTypeHeader();

      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }

      $objectid = JRequest::getInt('objectid',0);
      $model = new PCalendarModellistview();
      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      if(!$model->setOfferResult()) {
         jexit(jsonError('网络异常，请刷新重试!', null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function declinesend(){
      OC_JSON::setContentTypeHeader();
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }
      $user = PFactory::getMasterUser();
      // $jobid = JRequest::getInt('jobid', 0);
      $objectid = JRequest::getInt('objectid',0);

      // NOTE: This is a duplicate check of below check
      // if ( !PCompanyHelper::checkJobManagerPermissions($jobid) )
         // jexit(jsonError('您没有此操作权限！', null, false));

      $model = new PCalendarModellistview();
      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      $jobseekerid = JRequest::getInt('jobseekerid', 0);
      $jobseekerinfo = $model->getJobseekerInfo($jobseekerid);
      if(empty($jobseekerinfo))
         jexit(jsonError('网络异常，请刷新重试!', null, false));
      
      list($round, $total) = $model->getInterviewRound($jobseekerid);

      $objectid = JRequest::getInt('objectid', 0);
      if(!$model->setSendDeclineStatusByObjectid($objectid))
         jexit(jsonError('网络异常，请刷新重试!', null, false));

      $user = PCalendarHelper::getUserInformation();
      // Send email
      $model->sendDeclineEmail($jobseekerinfo, $round, $total, $user);

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function setinterviewfeedback(){
      $companyid = 0;
      if(!OC_User::isLoggedIn()) {
         $app = PFactory::getApplication();
         $companyid = $app->getUserState('calendarshare_companyid', 0);
         if(!$companyid) {
            jexit(jsonError("您没有管理该面试日程的权限！", null, false));
         }
      } else {
         if (PFactory::isJobseekerUser()) {
            jexit(jsonError("您没有管理该面试日程的权限！", null, false));
         } else {
            $user = PFactory::getMasterUser();
            $companyid = $user->id;
         }
      }

      OC_JSON::setContentTypeHeader();
      $model = new PCalendarModellistview();
      if(!$model->setInterviewFeedbackByObjectid($companyid)) {
         jexit(jsonError($model->getError(), null, false));
      }
      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function interviewfeedbackremind(){
      if ( !OC_User::isLoggedIn() ) {
         jexit(jsonError('请先登录！', null, false));
      }

      $jobid = JRequest::getInt('jobid',0);
      $objectid = JRequest::getInt('objectid',0);

      if ( empty($jobid) || empty($objectid) ) {
         jexit(jsonError('信息有误，请刷新重试！',null,false));
      }

      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      // NOTE: This is a duplicate check of above check
      // if ( !PCompanyHelper::checkJobManagerPermissions($jobid) ) {
      //    jexit(jsonError('对不起，您没有权限操作！', null, false));
      // }

      $user = PCalendarHelper::getInterviewerEmailDataFromObjectid($objectid);
      if ( empty($user) ) {
         jexit(jsonError('信息有误，请刷新重试！', null, false));
      } else {
         PCalendarHelper::sendFeedbackRemindEmail($user);
      }
      // Change the message "提醒发送成功！" to "发送成功！" here to fit preview event modal, since there is no space for 2 more words
      jexit(jsonSuccess('发送成功！', null, null, false));
   }

   public static function setentryresult(){
      OC_JSON::setContentTypeHeader();

      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
      }

      $objectid = JRequest::getInt('objectid',0);
      $model = new PCalendarModellistview();
      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      if(!$model->setEntryResult()) {
         jexit(jsonError('网络异常，请刷新重试!', null, false));
      }

      jexit(jsonSuccess('保存成功！', null, null, false));
   }

   public static function uploadoffertplfile(){
      if(!OC_User::isLoggedIn()) {
         jexit(jsonError('请先登录', null, false));
   	  }

      if (PFactory::isJobseekerUser()) {
         jexit(jsonError('您不是企业用户', null, false));
      }

      OC_JSON::setContentTypeHeader('text/plain');
      $objectid = JRequest::getInt('objid',0);
      $object_model = new PCalendarModelObject();
      // most likely it the post data is truncated because of larger file size than post_max_size or upload_max_filesize
      if(empty($objectid)){
         jexit(jsonError("文件超大，不支持该文件上传！", null, false));
      }
      // Check is this event belong to his company
      if ( !$object_model->checkObjectEditPermission($objectid) ) {
         jexit(jsonError("您没有该上传附件的权限！", null, false));
      }

      $model = new PCalendarModellistview();
      $return = $model->uploadAttachment();
      if(!$return) {
         jexit(jsonError($model->getError(), null, false));
      }
      else{
         jexit($return);
      }
   }
   
   public static function uploadInterviewfile(){ 
      if(!PUtil::checkUserLogin(true))
         return;
      OC_JSON::setContentTypeHeader('text/plain');
      $model = new PCalendarModellistview();
      jexit($model->uploadAttachment($type = 'interview'));
   }

   public static function cancelevent(){
      if(!OC_User::isLoggedIn()){
         jexit(jsonError('请先登录', null, false));
      }

      if(PFactory::isJobseekerUser()){
         jexit(jsonError('您不是企业用户', null, false));
      }

      $eventid = JRequest::getInt('eventid',0);
      $jobid = JRequest::getInt('jobid',0);
      $eventtype = JRequest::getString('eventtype','');
      $model = new PCalendarModellistview();
      $object_model = new PCalendarModelObject();

      // Check is this event belong to his company
      if(!$object_model->checkObjectEditPermission($eventid)){
         jexit(jsonError("您没有管理该面试日程的权限！", null, false));
      }

      //cancel event
      if(!($model->cancelEvent())){
         jexit(jsonError($model->getError(), null, false));
      }
      jexit(jsonSuccess('已取消', null, null, false));
   }

   public static function comfirmReject(){ 
      OC_JSON::setContentTypeHeader();
      $object_model = new PCalendarModelObject();  
      if(!$object_model->rejectoffer()) { 
         jexit(jsonError($object_model->getError(), null, false)); 
      }  
      jexit(jsonSuccess('操作成功！', null, null, false));   
   }
}
